package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @date: 2025/8/13 9:20
 * @author: yz
 * @version: 1.0
 */
@Aspect
@Component
public class GuiGuLoginAspect {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 定义用户拦截认证的切面实现
     * @param joinPoint
     * @return
     * @throws Throwable
     */
//    @Around("@annotation(com.atguigu.tingshu.common.login.GuiGuLogin)")
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public Object doConcurrentOperation(ProceedingJoinPoint joinPoint,GuiGuLogin guiGuLogin) throws Throwable {

        Object obj = new Object();
        //获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取请求头中token
        String token = request.getHeader("token");
        //定义redis访问key
        String key= RedisConstant.USER_LOGIN_KEY_PREFIX+token;

        //尝试获取数据
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(key);

        //判断认证拦截
        if(userInfoVo==null&&guiGuLogin.required()){


            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        //知道是登录还是没登录吗？
        if(userInfoVo!=null){

            AuthContextHolder.setUserId(userInfoVo.getId());
            AuthContextHolder.setUsername(userInfoVo.getNickname());
        }


        //放行去执行目标方法
        Object proceed = joinPoint.proceed();

        //释放线程变量中的数据
        AuthContextHolder.removeUserId();
        AuthContextHolder.removeUsername();
        return proceed;
    }
}
